<template>
  <div class="borrower">

    <el-card class="box-card" shadow="never" style="border:0px;">
      <!-- 查询结果 -->
      <el-table v-loading="loading" :data="tableData" size="small" element-loading-text="正在查询中。。。" :header-cell-style="{background:'#F7F7F8',color:'#606266'}" fit highlight-current-row>
        <el-table-column align="center" label="文件名称" prop="fileTypeName">
          <template slot-scope="scope">
            <span style="color:red">*</span><span>{{scope.row.fileTypeName.replace("*","")}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="文件数量" prop="fileNum"/>
        <el-table-column align="center" label="上传时间" prop="uploadTime"/>
        <el-table-column align="center" label="角色" prop="createRoleName"/>
        <el-table-column align="center" label="操作人" prop="createName"/>

        <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="uploadFile(scope.row)" v-permission="'system:credit-loan-file-upload:access'">上传文件</el-button>
            <el-button type="success" size="mini" @click="findDetailFile(scope.row)" v-permission="'system:credit-loan-file-look-detail:access'">查看文件</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" class="row-bg" justify="center" style="margin-top:50px;">
        <el-col :span="10">
          <el-button  type="primary" @click="backStep" style="width:120px;height:40px;" v-if="isProjectSubmit">上一步</el-button>
          <el-button  type="warning" @click="createData" style="width:120px;height:40px;" v-if="isProjectSubmit">预览</el-button>
          <el-button :loading="loading" type="primary" @click="exportData" style="width:150px;height:40px;display:block;margin:0 auto;" v-else v-permission="'system:credit-loan-file-batch-download:access'">批量下载</el-button>
        </el-col>
      </el-row>

      <!-- 附件展示图 -->
      <el-dialog :title="dialogStatusTitle" :visible.sync="detailDialogFormVisible" :close-on-click-modal="false" style="width: 90%; margin-left:150px;">
        <el-table v-loading="loading" :data="detailTableData" size="small" element-loading-text="正在查询中。。。" :header-cell-style="{background:'#F7F7F8',color:'#606266'}" fit highlight-current-row>
          <el-table-column align="center" label="文件名称" prop="fileName"> </el-table-column>
          <el-table-column align="center" label="上传时间" prop="uploadTime"/>
          <el-table-column align="center" label="角色" prop="createRoleName"/>
          <el-table-column align="center" label="操作人" prop="createName"/>
          <el-table-column align="center" label="附件" width="120" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-image width="100%" :src="scope.row.thumbUrl" :preview-src-list="[scope.row.fileUrl]"></el-image>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button type="info" size="mini" @click="logicDelete(scope.row)" v-permission="'system:credit-loan-file-delete:access'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" class="row-bg" justify="center" style="margin-top:50px;">
          <el-col :span="10" align="center">
            <el-button type="danger" @click="detailDialogFormVisible = false" style="width:150px;height:40px;">关闭窗口</el-button>
          </el-col>
        </el-row>
        <vxe-pager
          class="pager"
          @page-change="changePage"
          :current-page.sync="detailListQuery.pageNo"
          :page-size.sync="detailListQuery.pageSize"
          :total="total"
          :page-sizes="[10, 30, 50,100]"
          :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
        >
        </vxe-pager>
      </el-dialog>

      <!-- 添加或修改对话框 -->
      <el-dialog :title="dialogStatusTitle" :visible.sync="dialogFormVisible" :close-on-click-modal="false" >
        <el-form ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 90%; margin-left:50px;">
          <el-form-item label="文件列表" prop="fileUrlList">
            <el-upload
              style="margin-top:30px;"
              class="upload-demo"
              drag
              :action="creditLoanUploadFile"
              :file-list="galleryFileList"
              :headers="headers"
              :before-upload="handleBeforeUpload"
              :on-error="handleUploadError"
              :on-success="handleGalleryUrl"
              :on-preview="handlePictureCardPreview"
              :on-remove="physicalDeletion"
              :on-exceed="handleUploadLimit"
              accept=".jpg,.jpeg,.png,.gif,.pdf"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small"  @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" size="small" @click="updateData">确定上传</el-button>
        </div>
      </el-dialog>

      <el-dialog title="预览" :visible.sync="dialogFormVisiblePic" :close-on-click-modal="false">
        <img  v-if="handleShowFileType(dialogImageUrl)" width="100%" :src="dialogImageUrl" alt="">
        <iframe :src="dialogImageUrl"  width="100%" height="600px"></iframe>
      </el-dialog>
    </el-card>
    <el-dialog
      title="批量下载进度"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :show-close="false"
      width="30%"
      top="300px"
    >
      <el-progress :percentage="percentage" :color="customColor"></el-progress>
    </el-dialog>
  </div>
</template>

<style>
  .demo-image__preview{
    width: 100px;
    height: 100px;
    margin:0 auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
  import { mapGetters } from 'vuex';
  import { getToken } from '@/utils/auth'
  import { listFileByProjecId,deleteProjectFile,exportFile } from '@/api/projectFile'
  import { listFiles,saveFile,creditLoanUploadFile,batchUpdateFile,findDetailFile,logicDelete,physicalDeletion,batchDownload} from '@/api/creditLoanFile'
  import pdf from 'vue-pdf'
  export default {
    name: 'file',
    components: { pdf },
    // 接受父组件的值
    props: {
      isTaskProcessing: undefined,
      isProjectSubmit: undefined,
      changeValue: undefined,
      isNeedSubmit: undefined,
      projectId: undefined,
      projectStatus: undefined,
      operationLook: undefined,
      taskId: undefined,
      realName:undefined
    },
    data() {
      return {
        creditLoanUploadFile,
        defaultProjectId: undefined,
        total: 0,
        previewPicUrlList:[],
        galleryFileList:[],
        beforeArr:[],
        dialogImageUrl: undefined,
        detailListQuery: {
          pageNo: 1,
          pageSize: 5,
          entityId: undefined,
          fileTypeName: undefined,
          fileType: undefined
        },
        dataForm: {
          fileTypeName: undefined,
          fileNum: undefined,
          createTime: undefined,
          description:undefined,
          createName:undefined,
          picUrl: undefined
        },
        dialogFormVisible: false,
        dialogFormVisiblePic: false,
        dialogStatus: 'create',
        dialogStatusPic:'',
        dialogStatusTitle: undefined,
        dialogFormVisibleDetail: false,
        data: [{}],
        downloadLoading: false,
        tableData: [],
        detailTableData: [],
        detailDialogFormVisible: false,
        loading:false,
        dialogVisible:false,
        percentage:0,
        customColor: '#409eff',
      }
    },
    computed: {
      ...mapGetters(['roles']),
      headers() {
        return {
          'Authorization': "Bearer-"+getToken()
        }
      }
    },
    created() {
      this.defaultProjectId = this.$route.query.projectId
      if (this.defaultProjectId === undefined){
        this.defaultProjectId = localStorage.getItem('projectId');
      }
      this.listFiles()
    },
    methods: {
      //取消默认行为
      allowDrop(e){
        e.preventDefault();
      },
      //开始拖动
      dragStart(e, index){
        let tar = e.target;
        e.dataTransfer.setData('Text', index);
      },
      //放置
      drop(e, index){
        var temp;
        var temp1;
        this.allowDrop(e);
        console.log(this.dataForm.fileIdList)
        let arr1 = this.dataForm.fileIdList.concat([]);
        let arr = this.dataForm.fileUrlList.concat([]),
          dragIndex = e.dataTransfer.getData('Text');
        temp = arr.splice(dragIndex, 1);
        temp1 = arr1.splice(dragIndex, 1);
        arr.splice(index, 0, temp[0]);
        arr1.splice(index, 0, temp1[0]);
        console.log(arr1)
        this.dataForm.fileUrlList = arr;
        this.dataForm.fileIdList = arr1;
        this.$notify.success("图片位置拖动成功")

      },
      handlePreviewPdf(item){
        this.dialogImageUrl = item
        this.dialogFormVisiblePic = true
      },
      handleShowFileType(item){
        if( item!=undefined &&  item.indexOf("pdf")==-1){
          return true
        }
        return false
      },
      handleShowFlag(row) {
        if(this.operationLook) {
          return false
        }
      },
      handleFileType(row){
        if( row.fileTypeName.indexOf("*") !=-1 ){
          return true
        }
        return false
      },
      listFiles() {
        this.loading = true
        //这里多传个loanType参数来区分房抵贷还是信用贷
        listFiles(this.defaultProjectId)
          .then(response => {
            this.tableData = response.data
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
      },

      logicDelete(row) {
        this.$confirm('此操作删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          logicDelete({fileId:row.id}).then(response => {
            this.loading= false
            this.findDetailFile(row)
            this.$notify.success({title: '成功',message: '操作成功'})
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
          this.$message({type: 'info',message: '已取消删除'});
        });
      },

      changePage(){
        this.detailListQuery.entityId = this.defaultProjectId
        this.findDetailFile(this.detailListQuery);
      },
      // 查看项目附件
      findDetailFile(row) {
        this.dialogStatusTitle = row.fileTypeName
        this.loading = true
        this.detailDialogFormVisible = true;
        this.detailListQuery.fileType = row.fileType
        this.detailListQuery.entityId = this.defaultProjectId
        //这里多传个loanType参数来区分房抵贷还是信用贷
        findDetailFile(this.detailListQuery).then(response => {
            this.loading = false
            this.detailTableData = response.data
            this.total = response.total
          }).catch(() => {
            this.loading = false
          })
      },
      resetForm() {
        this.dataForm = {
          fileTypeName: undefined,
          fileNum: undefined,
          createTime: undefined,
          description:undefined,
          createName:undefined,
          picUrl: undefined

        }
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true

        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      uploadPicUrl: function(response) {
        this.dataForm.picUrl = response.data.fileUrl
        this.dataForm.fileId = response.data.id
      },
      handleUploadError(res){
        this.$message({
          type: 'error',
          message: '上传文件失败'
        })
      },
      handleBeforeUpload(file){
        console.log(file)
        let beforeArrFlag = true
        this.beforeArr.forEach((item,index)=>{
          if( item.uid!=undefined && item.uid == file.uid) {
            beforeArrFlag = false
          }
        })
        if( beforeArrFlag ) {
          this.beforeArr.push(file)
          this.dataForm.fileUrlList.push(file)
          this.dataForm.fileIdList.push(file)
        }
      },
      handleGalleryUrl(response, file, fileList) {
        try{
          console.log(this.dataForm.fileIdList)
          if(this.dataForm.fileUrlList === undefined){
            this.dataForm.fileUrlList = []
            this.dataForm.fileIdList = []
          }
          if (response.code === 20000) {
            for( let i=0 ; i< this.beforeArr.length; i++){
              if( this.beforeArr[i].uid == file.uid) {
                this.dataForm.fileUrlList.splice(i,1,{id:response.data.id,fileUrl:response.data.fileUrl,fileName:response.data.fileName})
                // this.dataForm.fileIdList.splice(i,1,{fileId:response.data.id})
                this.dataForm.fileIdList.splice(i,1,response.data.id)
              }
            }
          }
        }catch(error){
          this.$message.error(error)
        }finally{
        }
      },
      physicalDeletion: function(file, fileList) {
        try{
          for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
            var url
            if (file.response === undefined) {
              url = file.url
            } else {
              url = file.response.data.fileUrl
            }
            if (this.dataForm.fileUrlList[i].fileUrl === url) {
              physicalDeletion({fileId:this.dataForm.fileUrlList[i].id}).then(() => {

                }).catch(response => {})
              this.dataForm.fileUrlList.splice(i, 1)
              this.dataForm.fileIdList.splice(i, 1)
              this.beforeArr.splice(i, 1)
            }
          }
          console.log(this.dataForm.fileUrlList)
        }catch(error){
          this.$message.error(error)
        }finally{

        }
      },
      handleUploadLimit(){
        this.$message.error("仅可以上传20个文件");
      },
      handlePictureCardPreview(file){
        console.log(file)
        if( file.response!=undefined){
          this.dialogImageUrl = file.response.data.fileUrl
        }else{
          this.dialogImageUrl = file.fileUrl
        }
        this.dialogFormVisiblePic = true
      },
      backStep(){
        this.$emit("stepChanged",2)
      },
      createData() {
        this.$emit("stepChanged",4)
      },
      uploadFile(row) {
        this.dataForm = Object.assign({}, row)
        this.beforeArr = []
        if( this.dataForm.fileUrlList!=undefined && this.dataForm.fileUrlList.length>0){
          this.beforeArr = Object.assign([],this.dataForm.fileUrlList)
        }
        if( this.dataForm.fileUrlList == undefined ) {
          this.dataForm.fileUrlList = []
          this.dataForm.fileIdList = []
        }
        this.dialogStatusTitle = row.fileTypeName
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.galleryFileList = []
        if( this.dataForm.fileIdList!=undefined && this.dataForm.fileIdList.length>0){
          for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
            this.galleryFileList.push({
              name: this.dataForm.fileUrlList[i].fileName,
              url: this.dataForm.fileUrlList[i].fileUrl
            })
          }
        }
      },
      lookFile(row) {
        console.log(row)
        this.dataForm = Object.assign({}, row)
        // this.dataForm.picUrl = undefined
        //  this.galleryFileList = []
        if( this.dataForm.fileIdList!=undefined && this.dataForm.fileIdList.length>0){
          for (var i = 0; i < this.dataForm.fileUrlList.length; i++) {
            // this.galleryFileList.push({
            //   url: this.dataForm.fileUrlList[i].fileUrl
            // })
            if( this.dataForm.fileUrlList[i].fileName.indexOf("pdf")==-1){
              this.previewPicUrlList.push(this.dataForm.fileUrlList[i].fileUrl)
            }
          }
        }

        // this.picUrlList = row.fileUrlList
        this.dialogStatusPic = row.fileTypeName
        this.dialogFormVisibleDetail = true
      },

      // 文件最终保存接口
      updateData() {
        let flag = false
        if( this.dataForm.fileIdList == undefined || this.dataForm.length==0){
          flag = true
        }else{
          this.dataForm.fileIdList.forEach((item,index)=>{
            if( item==undefined) {
              flag = true
            }
          })
        }
        if( flag ) {
          this.$message.error("请稍等，您选择的文件还没有上传成功哦")
          return false
        }
        this.dataForm.entityId = this.defaultProjectId
        this.dataForm.sourceEntity = 'projectInfo'
        this.loading = true
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            batchUpdateFile(this.dataForm).then(() => {
                this.loading = false
                this.listFiles()
                this.dialogFormVisible = false
                this.$notify.success({title: '成功',message: '保存成功'})
              }).catch(response => {
                this.loading = false
              })
          }
        })
      },
      createDataFile() {
        this.dataForm.projectId = this.defaultProjectId
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            saveFile(this.dataForm).then(() => {
                this.loading = true
                this.listFiles()
                this.dialogFormVisibleDetail = false
                this.$notify.success({title: '成功',message: '保存成功'})
              }).catch(response => {
              })
          }
        })
      },
      // projectId: this.projectId
      // exportData() {
      //   this.loading = true
      //   batchDownload(this.projectId).then((res) => {
      //     this.loading = false
      //     setTimeout(() => {
      //       const content = res
      //       const blob = new Blob([content],{ type: 'application/zip' })
      //       const fileName = this.realName+'附件.zip'
      //       if ('download' in document.createElement('a')) { // 非IE下载
      //         const elink = document.createElement('a')
      //         elink.download = fileName
      //         elink.style.display = 'none'
      //         elink.href = URL.createObjectURL(blob)
      //         document.body.appendChild(elink)
      //         elink.click()
      //         URL.revokeObjectURL(elink.href) // 释放URL 对象
      //         document.body.removeChild(elink)
      //       } else { // IE10+下载
      //         navigator.msSaveBlob(blob,fileName)
      //       }
      //       this.loading = false
      //     },1000)
      //   }).catch(response => {
      //     this.loading = false
      //   })
      // },
      exportData() {
        this.loading = true
        batchDownload(this.projectId).then((res) => {
          this.loading = false
          setTimeout(() => {
            const content = res
            const blob = new Blob([content],{ type: 'application/zip' })
            const fileName = this.realName+'附件.zip'
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else { // IE10+下载
              navigator.msSaveBlob(blob,fileName)
            }
            this.loading = false
          },1000)
        }).catch(response => {
          this.loading = false
        })
      },
    }
  }
</script>
